package com.wiscamp.ninechapters.problems.infrastructure.mappers.collections;

import com.wiscamp.ninechapters.problems.infrastructure.po.collections.CollectionProblemPO;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * 题集及题关联仓储对象
 *
 * @author yifeng
 */
@Repository
public interface CollectionProblemMapper extends JpaRepository<CollectionProblemPO, Long>, JpaSpecificationExecutor<CollectionProblemPO> {

    /**
     * 通过题编号获取题集与题关联
     *
     * @param problemId
     * @return
     */

    @Query(value = "select e from CollectionProblemPO e where e.problemId = :problemId")
    CollectionProblemPO findByProblem(long problemId);

    @Query(value = "select e from CollectionProblemPO e where  e.collectionId = :collectionId and e.problemId = :problemId")
    CollectionProblemPO findByProblem(long collectionId, long problemId);

    @Query(value = "select max(pi.problemIndex) from CollectionProblemPO pi where pi.collectionId = :collectionId")
    Integer findMaxProblemIndex(long collectionId);

    @Query(value = "select e from CollectionProblemPO e where e.collectionId = :collectionId and e.problemIndex = :index")
    CollectionProblemPO findByIndex(long collectionId, int index);

    @Query(value = "select e from CollectionProblemPO e, ProblemPO i where e.problemId = i.problemId and e.collectionId = :collectionId and i.deleted = false order by e.problemIndex")
    Collection<CollectionProblemPO> findListByCollection(long collectionId);

    @Query(value = "select e.problemId from CollectionProblemPO e, ProblemPO i where e.problemId = i.problemId and e.collectionId = :collectionId and i.deleted = false order by e.problemIndex")
    Collection<Long> findProblemIdsByCollection(long collectionId);

    @Transactional
    @Modifying
    @Query(value = "update CollectionProblemPO e set e.problemIndex = e.problemIndex - 1 where e.collectionId = :collectionId and e.problemIndex > :index")
    void resortProblemIndex(long collectionId, int index);
}